#web页面显示温湿度线状图
#后台使用fastapi做网页框架，tinydb做数据库，显示通过pyecharts显示线状图，并设计了包含各类配置的web管理
#另一个程序每分钟从温湿度计上，蓝牙读取小米温湿度计2的温湿度和电池数据，并tinydb数据库写入当天的json文件中。
from fastapi import FastAPI
from starlette.responses import HTMLResponse
import uvicorn
#from pyecharts import options as opts
#from pyecharts.charts import Line
import os,sys,time,datetime
#from pyecharts.components import Table
#from pyecharts.options import ComponentTitleOpts
from starlette.staticfiles import StaticFiles
#from pyecharts.globals import CurrentConfig
#from tinydb import TinyDB, Query
from typing import Optional
from starlette.responses import RedirectResponse

#主菜单
main_menu='''
<br><a href="./admin">1.admin</a></br>
<br><a href="http://111.75.203.245:83">2.ETSI search</a></br>
'''


#管理菜单
admin_menu='''
<br><a href="./reset_hosts.deny">1.重置hosts.deny</a></br>
<br><a href="./start_tinyproxy">2.start tinyproxy</a></br>
<br><a href="./stop_tinyproxy">3.stop tinyproxy</a></br>
'''
#密码表单
password_form='''
<form name="input" action="?" method="get">
Password: <input type="password" name="pwd">
<input type="submit" value="Submit">
</form>
'''


app = FastAPI()

#加载static目录，包含一些js文件
app.mount('/static', StaticFiles(directory='/home/wjb711/static'), name='static')
@app.get("/")
def root():
    return HTMLResponse(content=main_menu)
    #return RedirectResponse(url='/admin')


#管理界面
@app.get("/admin")
def admin(pwd: Optional[str] = None):
    if pwd=='rootpasswd':
        return HTMLResponse(content=admin_menu)
    else:

        return HTMLResponse(content=password_form)
@app.get('/reset_hosts.deny')
def reset():
    os.system('echo "" > /etc/hosts.deny')
    return  HTMLResponse(content='reset hosts.deny')
@app.get('/stop_tinyproxy')
def stop_tinyproxy():
    os.system('systemctl stop tinyproxy')
    return  HTMLResponse(content='systemctl stop tinyproxy')
@app.get('/start_tinyproxy')
def start_tinyproxy():
    os.system('systemctl start tinyproxy')
    return  HTMLResponse(content='systemctl start tinyproxy')

#主函数定义端口
if __name__ == "__main__":
    #print('当前程序名称为:',os.path.basename(__file__))
    #filename=os.path.basename(__file__).split('.')[0]
    filename=os.path.basename(sys.argv[0]).split('.')[0]
    #print(filename,os.getcwd(),os.path.dirname(os.path.realpath('__file__')))
    #os.chdir(current_path)
    #uvicorn.run('{}:app'.format(filename), host="0.0.0.0",port=8888,log_level="info",workers=5,reload=True)
    uvicorn.run('{}:app'.format(filename), host="0.0.0.0",port=8888,log_level="info",workers=5,reload=True)